package com.aivin.lib_login.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.aivin.lib_base.config.SaveConfig;
import com.aivin.lib_base.tool.CacheSaveTool;
import com.aivin.lib_base.tool.MyDeviceInforHelper;
import com.aivin.lib_base.tool.RouteUtils;
import com.aivin.lib_base.tool.WkLog;
import com.aivin.lib_login.R2;
import com.aivin.lib_widget.MaterialButton;
import com.aivin.lib_login.R;
import com.aivin.lib_login.bean.AppPassWord;
import com.aivin.lib_login.bean.LoginInfo;
import com.aivin.lib_widget.MyTextureView;
import com.aivin.lib_widget.NineGridLayout;
import com.aivin.lib_widget.ScaleImage;
import com.aivin.lib_widget.WkExpandLayout;
import com.aivin.lib_widget.base.BaseActivity;
import com.alibaba.android.arouter.launcher.ARouter;
import com.tencent.mmkv.MMKV;
import com.wind.me.xskinloader.SkinInflaterFactory;
import com.wind.me.xskinloader.SkinManager;
import com.wind.me.xskinloader.util.AssetFileUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;


/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity {
    @BindView(R2.id.infoTv)
    TextView infoTv;
    @BindView(R2.id.userPassword)
    EditText userPassword;
    @BindView(R2.id.savePwd)
    public CheckBox savePwd;
    @BindView(R2.id.wkExpandOhterFunc)
    WkExpandLayout wkExpandOhterFunc;

    private MediaPlayer player;
    private MediaPlayer mMediaPlayer;
    private Context context;
    @BindView(R2.id.textureView)
    MyTextureView textureView;
    @BindView(R2.id.nineGridLayout)
    NineGridLayout nineGridLayout;
    @BindView(R2.id.changeStateBtn)
    ImageView changeStateBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.lib_login_activity_login);
        ButterKnife.bind(this);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        context = getApplicationContext();
        initView();
        initCache();
        initVideoView();
        initPlayer();
        requestPermission(this);

        TextView appInfo = findViewById(R.id.appInfo);
        String appVerionName = MyDeviceInforHelper.getAppVersion(this);
        appInfo.setText(appVerionName);


    }


    @OnClick({R2.id.changeStateBtn})
    public void onViewClicked(View view) {
        int id = view.getId();

        if (id == R.id.changeStateBtn) {
            changeExpandUI() ; // changeStateBtn
        }
    }


    private boolean isActivityAtTop =false ;
    @Override
    protected void onResume() {
        super.onResume();
        isActivityAtTop =true ;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivityAtTop = false ;
    }

    private void changeExpandUI(){
        // activity 不在前台显示就不处理
        if(!isActivityAtTop){
            return;
        }
        boolean expaded =wkExpandOhterFunc.toggleExpand(false);
        int resourceId =expaded ? R.mipmap.lib_login_down : R.mipmap.lib_login_up;
        changeStateBtn.setImageResource(resourceId);
    }

    private void initPlayer() {
        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {

            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                if (mMediaPlayer == null) {
                    mMediaPlayer = new MediaPlayer();
                    mMediaPlayer.setSurface(new Surface(surface));

                    mMediaPlayer.setOnPreparedListener(mp -> {
                        mMediaPlayer.setVolume(0, 0);// 静音
                        mMediaPlayer.setLooping(true);
                        mMediaPlayer.start();

                    });


                    mMediaPlayer.setOnVideoSizeChangedListener((mp, width1, height1) -> {
                        //updateTextureViewSizeCenterCrop(mp ,textureView);
                        updateTextureViewSizeCenter(mp ,textureView);
                    });

                    try {
                        mMediaPlayer.setDataSource(context, Uri.parse("android.resource://" +
                                getPackageName() + "/" + R.raw.raw_flower2));
                        mMediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                if (mMediaPlayer != null) {
                    mMediaPlayer.release();
                    mMediaPlayer = null;
                }
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });

        View testGroup = findViewById(R.id.testGroup);
        textureView.setOnLocationChangeCallBack((x, y) -> {
            int rightMax = MyDeviceInforHelper.getWindowWidth(testGroup.getContext()) - testGroup.getWidth();
            int navigationBarHeight = MyDeviceInforHelper.getNavigationBarHeight(this);
            int statusBarHeight = MyDeviceInforHelper.getStatusBarHeight(this);
            int topMax = MyDeviceInforHelper.getWindowHeigh(testGroup.getContext()) - testGroup.getHeight() + navigationBarHeight + statusBarHeight;

            float posionX = testGroup.getX() + x;
            posionX = posionX <= 0 ? 0 : posionX;
            posionX = posionX >= rightMax ? rightMax : posionX;
            testGroup.setX(posionX);  //

            float positionY = testGroup.getY() + y;
            positionY = positionY <= 0 ? 0 : positionY;

            positionY = positionY >= topMax ? topMax : positionY; //
            testGroup.setY(positionY);
        });


        ScaleImage scaleImage = findViewById(R.id.ivScale);
        scaleImage.setOnScaleCallBack((x, y) -> {
            float scalK = textureView.getSacaleK();
            if (scalK == -1) {
                return;
            }

            int newX = (int) Math.abs(y * scalK);
            newX = y > 0 ? -newX : newX;

            ViewGroup.LayoutParams layoutParams = testGroup.getLayoutParams();
            layoutParams.width = layoutParams.width + newX;
            layoutParams.height = layoutParams.height - y;
            testGroup.setLayoutParams(layoutParams);
        });

    }


    /**
     * centerCrop 效果
     */
    private void updateTextureViewSizeCenterCrop(MediaPlayer mediaPlayer ,MyTextureView textureView){
        int videoWidth = mediaPlayer.getVideoWidth() ;
        int videoHeight =  mediaPlayer.getVideoHeight() ;
        int viewWidth = textureView.getWidth();
        int viewHeight = textureView.getHeight();
        float sx = viewWidth*1f / viewHeight;
        float sy = viewHeight*1f / videoHeight ;

        Matrix matrix = new Matrix();
        float maxScale = Math.max(sx, sy);
        //第1步:把视频区移动到View区,使两者中心点重合.
        matrix.preTranslate((viewWidth - videoWidth) / 2f, (viewHeight - videoHeight) / 2f);
        //第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
        matrix.preScale(videoWidth / (float) viewWidth, videoHeight / (float) viewHeight);
        //第3步,等比例放大或缩小,直到视频区的一边超过View一边, 另一边与View的另一边相等. 因为超过的部分超出了View的范围,所以是不会显示的,相当于裁剪了.
        matrix.postScale(maxScale, maxScale, viewWidth / 2f, viewHeight / 2f);
        textureView.setTransform(matrix);
        textureView.postInvalidate();
    }


    /**
     * center 效果
     */
    private void updateTextureViewSizeCenter(MediaPlayer mediaPlayer ,MyTextureView textureView){
        int videoWidth = mediaPlayer.getVideoWidth() ;
        int videoHeight =  mediaPlayer.getVideoHeight() ;
        int viewWidth = textureView.getWidth();
        int viewHeight = textureView.getHeight();
        float sx =  viewWidth*1f  /  videoWidth;
        float sy =  viewHeight*1f  /  videoHeight;

        Matrix matrix = new Matrix();
        //第1步:把视频区移动到View区,使两者中心点重合.
        matrix.preTranslate((viewWidth - videoWidth) / 2.f, (viewHeight - videoHeight) / 2.f);
        //第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
        matrix.preScale(videoWidth*1f / viewWidth , videoHeight*1f /  viewHeight);
        //第3步,等比例放大或缩小,直到视频区的一边和View一边相等.如果另一边和view的一边不相等，则留下空隙
        if (sx >= sy){
            matrix.postScale(sy, sy, viewWidth / 2f, viewHeight / 2f);
        }else{
            matrix.postScale(sx, sx, viewWidth / 2f, viewHeight / 2f);
        }
        textureView.setTransform(matrix);
        textureView.postInvalidate();
    }


    /**
     * 获取缓存，初始化配置
     */
    private void initCache() {
        String pwd = CacheSaveTool.getInstance().getString(SaveConfig.KEY_PWD, MMKV.defaultMMKV());
        if (pwd != null) {
            savePwd.setChecked(true);
            userPassword.setText(pwd);
        }
    }


    private void initVideoView() {
        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                player = new MediaPlayer();
                player.setDisplay(holder);
                player.setOnPreparedListener(mp -> {

                    player.setVolume(0, 0);// 静音
                    player.setLooping(true);
                    player.start();
                });

                try {
                    player.setDataSource(context, Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.welcome2));
                    player.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
                    player.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (player != null) {
                    player.stop();
                    player.release();
                }
            }
        });
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        if(action==MotionEvent.ACTION_DOWN ){
            if(countDownTimer!=null){
                countDownTimer.cancel();
            }
        }

        else if (action==MotionEvent.ACTION_UP ){
            startCount(); //dispatchTouchEvent
        }
        return super.dispatchTouchEvent(ev);
    }


    private CountDownTimer countDownTimer ;
    public void startCount() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(5 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {   }

                @Override
                public void onFinish() {
                    changeExpandUI() ; //onFinish
                }
            };
        }
        countDownTimer.start();
    }


    private boolean userWantToSave = false;

    private void initView() {
        savePwd.setOnCheckedChangeListener((buttonView, isChecked) -> {

            boolean isFromUser = buttonView.isPressed();
            if (isFromUser) {
                userWantToSave = isChecked;
                if (!isChecked) {
                    removePwdCache(true);
                }
            }

        });

        MaterialButton loginBtn = findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(v -> {
            String password = userPassword.getText().toString().trim();
            if (password.equals("")) {
                infoTv.setText(getString(R.string.str_pwdIsnull));
                return;
            }

            infoTv.setText(getString(R.string.str_isloading));
            userLogin(password);
        });

        wkExpandOhterFunc.initExpandViewConfig(false, 0, 500);
        startCount(); // init

        List<Integer> imageList = Arrays.asList(
                R.mipmap.kungfu,
                R.mipmap.english,
                R.mipmap.jpan ,
                R.mipmap.skin
        );
        nineGridLayout.setUrlList(imageList);
        nineGridLayout.setOnNiewGridLayoutItemClickListner(new NineGridLayout.OnNiewGridLayoutItemClickListner() {
            @Override
            public void onItemClick(int index) {
                changeExpandUI(); // onItemClick
                if(index== 0){
                    ARouter.getInstance().build(RouteUtils.BookshelfActivity).navigation();
                }
                else if(index ==1 ){
                    ARouter.getInstance().build(RouteUtils.EnglishListActivity).navigation();
                }

                else if(index ==2 ){
                    ARouter.getInstance().build(RouteUtils.JapneseShowActivity).navigation();
                }

                else if(index ==3 ){
                     //换肤
                    changeSkin();
                }

            }
        });
    }

    private boolean isDefalutSkin = true ;
    private void changeSkin(){
        if(!isDefalutSkin){
            SkinManager.get().restoreToDefaultSkin();
        }else{
            loadSkinFromLocal();
        }
        isDefalutSkin = !isDefalutSkin ;
    }


    private void loadSkinFromLocal() {
        //将assets目录下的皮肤文件拷贝到data/data/.../cache目录下
        String saveDir = getCacheDir().getAbsolutePath() + "/skins";
        String savefileName = "skin1.skin";
        File file = new File(saveDir + File.separator + savefileName);
        if (!file.exists()) {
            String asset_dir = "skins/apk_skin_green-debug.apk";
            boolean result =AssetFileUtils.copyAssetFile(this, asset_dir, saveDir, savefileName);
            WkLog.showLog("copyAssetFile result is "+result+"  file="+file.getAbsolutePath());
        }
        SkinManager.get().loadSkin(file.getAbsolutePath());
    }



    private void userLogin(final String password) {
        BmobQuery<AppPassWord> query = new BmobQuery<>();
        query.addWhereEqualTo("userName", "Reader_temp");
        query.setLimit(50);
        query.findObjects(new FindListener<AppPassWord>() {
            @Override
            public void done(List<AppPassWord> object, BmobException e) {
                if (object == null) {
                    infoTv.setText(getString(R.string.str_loginFailed));
                    return;
                }

                boolean isOk = false;
                for (AppPassWord bean : object) {
                    if (bean.getUserPassword().equals(password)) {
                        isOk = true;
                        break;
                    }
                }

                if (!isOk) {
                    infoTv.setText(getString(R.string.str_pwdIsError));
                    removePwdCache(false);
                    return;
                }
                goNewActivity(password);
            }
        });

    }


    private void goNewActivity(String password) {
        infoTv.setText(getString(R.string.str_logonSuccess));

        if (userWantToSave) {
            savePwdCache(password);
        }
        saveLoginLog();
    }


    private void savePwdCache(String password) {
        int validTime = CacheSaveTool.TIME_DAY * 3;
        CacheSaveTool.getInstance().saveString(SaveConfig.KEY_PWD, password, validTime, MMKV.defaultMMKV());
    }

    private void removePwdCache(boolean byUser) {
        savePwd.setChecked(false);
        MMKV.defaultMMKV().remove(SaveConfig.KEY_PWD);
    }

    private void saveLoginLog() {
        String otherInfo = android.os.Build.MODEL + " " + android.os.Build.VERSION.SDK_INT;
        @SuppressLint("HardwareIds")
        String uuid = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setAppName(getPackageName());
        loginInfo.setOtherInfo(otherInfo);
        loginInfo.setUuid(uuid);
        loginInfo.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                ARouter.getInstance().build(RouteUtils.BookActivity).navigation();
                finish();
            }
        });
    }


    private void requestPermission(Activity activity) {
        // 在申请权限之前不用进行任何判断，AndPermission内部已经做了判断，如果有权限不会重复申请
        AndPermission.with(activity)
                .requestCode(100)
                .permission(
                        //sd
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                )
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(activity, rationale).show();
                    }
                })
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        // 权限申请成功回调。
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        toastMsg(getString(R.string.str_needPermission));
                    }
                })
                .start();
    }//


}